#version 120 

uniform sampler2DRect centers;
uniform sampler2DRect random;
uniform int nCenters;
uniform int flash;

varying vec3 worldPos;

vec3 rand() {
	return texture2DRect (random, worldPos.xy/10.0).xyz;
}

vec3 getPos (int centerId) {
	return texture2DRect (centers, vec2(centerId,0)).xyz;
} 
	
float getClass (int centerId) {
	return texture2DRect (centers, vec2(centerId,1)).x;	
}


void main() {

	float dMin = 999999.0;
	int found = -1;
	
	
	for (int i=0; i<nCenters; i++) {
		float d = abs(distance(worldPos, getPos(i)+rand()*5000));
		if (d<dMin && getClass(i)!=-1) {
			found = i;
			dMin = d;
		}
	}
	
	vec3 c = vec3(0,0,0);
	
	if (getClass(found)==0) c = vec3(1,0,0);
	if (getClass(found)==1) c = vec3(0.9,0.9,0.9);
	if (getClass(found)==2) c = vec3(0.2,0.2,0.7);
	if (getClass(found)==3) c = vec3(0,0,0);
	if (getClass(found)==4) c = vec3(0,0.5,1);
	if (getClass(found)==5) c = vec3(0,1,1);
	if (getClass(found)==6) c = vec3(1,0,0.5);
	if (getClass(found)==7) c = vec3(0.5,0,1);
	if (getClass(found)==8) c = vec3(0.5,1,0.5);
	if (getClass(found)==9) c = vec3(1,0.5,1);
	
	//if (gl_TexCoord[1].z>0 || gl_TexCoord[1].y>0.9 || gl_TexCoord[1].z>0.9) c = vec3(0,1,0);
	
	if (flash==1) c+=vec3(0.5,0.5,0.5);
	gl_FragColor = vec4(c,1); 
}